<template>
    <div class="student-management">
        <h2>学生管理</h2>
        <p>管理学生信息，包括查看、编辑、删除等操作</p>
        <div class="search-area">
            <el-input v-model="searchParams.name" placeholder="输入姓名" prefix-icon="el-icon-search"
                style="width: 300px" />
            <el-select v-model="searchParams.majorId" placeholder="全部专业" style="margin-left: 10px; width: 200px">
                <el-option v-for="major in majors" :key="major.id" :label="major.name" :value="major.id" />
            </el-select>
            <el-input v-model="searchParams.contactPhone" placeholder="输入联系电话"
                style="margin-left: 10px; width: 200px" />
            <el-button type="primary" @click="searchStudents">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
        </div>
        <div class="action-buttons">
            <el-button>导入</el-button>
            <el-button type="primary" @click="openAddDialog">添加学生</el-button>
            <el-button @click="exportSelectedStudents">批量导出</el-button>
            <el-button @click="refreshStudents">刷新</el-button>
        </div>
        <el-table :data="students" border style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="photo" label="头像" width="100">
                <template #default="scope">
                    <img v-if="scope.row.photo" :src="scope.row.photo" alt="avatar" style="width: 80px; height: 80px" />
                </template>
            </el-table-column>
            <el-table-column prop="studentId" label="学号" sortable />
            <el-table-column prop="name" label="姓名" sortable />
            <el-table-column prop="sex" label="性别">
                <template #default="scope">
                    {{ scope.row.sex == 0 ? '男' : '女' }}
                </template>
            </el-table-column>
            <el-table-column prop="majorName" label="专业" />
            <el-table-column prop="className" label="班级" />
            <el-table-column prop="contactPhone" label="联系电话" />
            <el-table-column prop="status" label="报到状态" />
            <el-table-column prop="paymentStatus" label="缴费状态" />
            <el-table-column prop="dormBuilding" label="入住地点" />
            <el-table-column prop="roomNumber" label="寝室号" />
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button type="text" @click="viewStudent(scope.row.id)">查看</el-button>
                    <el-button type="text" @click="editStudent(scope.row.id)">编辑</el-button>
                    <el-button type="text" @click="deleteStudent(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--分页-->
        <el-pagination v-if="total > 0" @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="total" />
        <div v-else style="text-align: center; padding: 20px">暂无数据</div>

        <!-- 学生信息模态框（添加/查看/编辑共用） -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
            <el-form :model="formData" label-width="120px" :disabled="isViewMode">
                <el-form-item label="学号">
                    <el-input v-model="formData.studentId" placeholder="请输入学号" />
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="formData.name" placeholder="请输入姓名" />
                </el-form-item>
                <el-form-item label="性别">
                    <el-radio-group v-model="formData.sex">
                        <el-radio :label="0">男</el-radio>
                        <el-radio :label="1">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="头像">
                    <el-upload 
                        class="avatar-uploader"
                        action="http://localhost:8080/upload" 
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess" 
                        :before-upload="beforeAvatarUpload"
                        :disabled="isViewMode">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="专业">
                    <el-select v-model="formData.majorId" placeholder="请选择专业">
                        <el-option v-for="major in majors" :key="major.id" :label="major.name" :value="major.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="班级">
                    <el-select v-model="formData.classId" placeholder="请选择班级">
                        <el-option v-for="clazz in clazzs" :key="clazz.id" :label="clazz.name" :value="clazz.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="联系电话">
                    <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
                </el-form-item>
                <el-form-item label="身份证号">
                    <el-input v-model="formData.idCard" placeholder="请输入身份证号" />
                </el-form-item>
                <el-form-item label="紧急联系人">
                    <el-input v-model="formData.emergencyContact" placeholder="请输入紧急联系人" />
                </el-form-item>
                <el-form-item label="紧急联系电话">
                    <el-input v-model="formData.emergencyPhone" placeholder="请输入紧急联系电话" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="closeDialog">关闭</el-button>
                    <el-button type="primary" v-if="!isViewMode" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>

    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { seartchApi, addStudentApi, getStudentByIdApi, updateStudentApi,deleteStudentApi,exportStudentApi } from "@/api/Student";
import { Plus } from '@element-plus/icons-vue'


//存储选中的id
const selectedStudentIds = ref([]);
//处理表格选中事件（提取选中项的id）
const handleSelectionChange = (selectedItems) => {
  // selectedItems 是选中的学生行数组，从每行中提取 id 存入 selectedStudentIds
  selectedStudentIds.value = selectedItems.map(item => item.id);
  // 可选：打印选中ID，方便调试
  console.log("选中的学生ID：", selectedStudentIds.value);
};

//批量导出为文件
const exportSelectedStudents = async () => {
    //打印参数类型
    console.log("导出的ID：", selectedStudentIds.value);
    const res=await exportStudentApi( selectedStudentIds.value);
    if(res.code==0){
        ElMessage.success("导出成功");
    }else{
        ElMessage.error("导出失败");
    }
}


// 图片相关
const imageUrl = ref('');
const handleAvatarSuccess = (res, file) => {
    imageUrl.value = URL.createObjectURL(file.raw);
    formData.photo = res.data;
};

// 限制上传图片类型和大小
const beforeAvatarUpload = (rawFile) => {
    const isJPG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png';
    const isLt2M = rawFile.size / 1024 / 1024 < 2;

    if (!isJPG) {
        ElMessage.error('上传头像图片只能是 JPG/PNG 格式!');
    }
    if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!');
    }
    return isJPG && isLt2M;
};

// 搜索参数
const searchParams = reactive({
    name: '',
    majorId: undefined,
    contactPhone: '',
});

// 表格数据
const students = ref([]);
const majors = ref([
    { id: 1, name: '软件工程' },
    { id: 2, name: '电子商务' },
    { id: 3, name: '计算机科学与技术' },
    { id: 4, name: '大数据' }
]);
const clazzs = ref([
    { id: 1, name: '软件工程1班' },
{ id: 2, name: '软件工程2班' },
{ id: 3, name: '软件工程3班' },
{ id: 7, name: '软件工程4班' },
{ id: 8, name: '软件工程5班' },
{ id: 9, name: '电子商务1班' },
{ id: 10, name: '电子商务2班' },
{ id: 11, name: '电子商务3班' },
{ id: 12, name: '电子商务4班' },
{ id: 13, name: '电子商务5班' },
{ id: 14, name: '计算机科学与技术1班' },
{ id: 15, name: '计算机科学与技术2班' },
{ id: 16, name: '计算机科学与技术3班' },
{ id: 17, name: '计算机科学与技术4班' },
{ id: 18, name: '计算机科学与技术5班' },
{ id: 19, name: '计算机科学与技术6班' },
{id: 20, name: '大数据1班'},
{id: 21, name: '大数据2班'},
{id: 22, name: '大数据3班'}
]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 模态框相关
const dialogVisible = ref(false);
const dialogTitle = ref('添加学生');
const isViewMode = ref(false); // 用于区分查看/编辑/添加模式
const formData = reactive({
    id: "",
    classId: "",
    contactPhone: "",
    dormId: "",
    idCard: "",
    majorId: "",
    name: "",
    photo: "",
    sex: 0,
    studentId: "",
    userId: "",
    emergencyContact: "",
    emergencyPhone: ""
});

// 搜索学生列表
const searchStudents = async () => {
    try {
        const response = await seartchApi({
            params: {
                ...searchParams,
                page: currentPage.value,
                pageSize: pageSize.value,
            },
        });
        students.value = response.data.rows;
        total.value = response.data.total;
    } catch (error) {
        ElMessage.error('获取学生列表失败');
        console.error(error);
    }
};

// 重置搜索
const resetSearch = () => {
    searchParams.name = '';
    searchParams.majorId = '';
    searchParams.contactPhone = '';
    searchStudents();
};

// 刷新列表
const refreshStudents = () => {
    searchStudents();
};

// 分页相关
const handleSizeChange = (val) => {
    pageSize.value = val;
    searchStudents();
};

const handleCurrentChange = (val) => {
    currentPage.value = val;
    searchStudents();
};

// 打开添加对话框
const openAddDialog = () => {
    dialogTitle.value = '添加学生';
    isViewMode.value = false;
    resetFormData();
    dialogVisible.value = true;
};

// 关闭对话框
const closeDialog = () => {
    dialogVisible.value = false;
    resetFormData();
};

// 重置表单数据
const resetFormData = () => {
    imageUrl.value = '';
    formData.id = "";
    formData.classId = "";
    formData.contactPhone = "";
    formData.dormId = "";
    formData.idCard = "";
    formData.majorId = "";
    formData.name = "";
    formData.photo = "";
    formData.sex = 0;
    formData.studentId = "";
    formData.userId = "";
    formData.emergencyContact = "";
    formData.emergencyPhone = "";
};

// 查看学生信息
const viewStudent = async (id) => {
    try {
        const response = await getStudentByIdApi(id);
        if (response.data) {
            // 填充表单数据
            const student = response.data;
            formData.id = student.id;
            formData.classId = student.classId || "";
            formData.contactPhone = student.contactPhone || "";
            formData.dormId = student.dormId || "";
            formData.idCard = student.idCard || "";
            formData.majorId = student.majorId || "";
            formData.name = student.name || "";
            formData.photo = student.photo || "";
            formData.sex = student.sex !== undefined ? student.sex : 0;
            formData.studentId = student.studentId || "";
            formData.userId = student.userId || "";
            formData.emergencyContact = student.emergencyContact || "";
            formData.emergencyPhone = student.emergencyPhone || "";
            
            // 设置头像
            imageUrl.value = student.photo || '';
            
            // 设置模态框状态
            dialogTitle.value = '查看学生信息';
            isViewMode.value = true;
            dialogVisible.value = true;
        } else {
            ElMessage.error('未找到该学生');
        }
    } catch (error) {
        ElMessage.error('获取学生信息失败');
        console.error(error);
    }
};

// 编辑学生信息
const editStudent = async (id) => {
    try {
        const response = await getStudentByIdApi(id);
        if (response.data) {
            // 填充表单数据，与查看类似
            const student = response.data;
            formData.id = student.id;
            formData.classId = student.classId || "";
            formData.contactPhone = student.contactPhone || "";
            formData.dormId = student.dormId || "";
            formData.idCard = student.idCard || "";
            formData.majorId = student.majorId || "";
            formData.name = student.name || "";
            formData.photo = student.photo || "";
            formData.sex = student.sex !== undefined ? student.sex : 0;
            formData.studentId = student.studentId || "";
            formData.userId = student.userId || "";
            formData.emergencyContact = student.emergencyContact || "";
            formData.emergencyPhone = student.emergencyPhone || "";
            
            // 设置头像
            imageUrl.value = student.photo || '';
            
            // 设置模态框状态
            dialogTitle.value = '编辑学生信息';
            isViewMode.value = false;
            dialogVisible.value = true;
        } else {
            ElMessage.error('未找到该学生');
        }
    } catch (error) {
        ElMessage.error('获取学生信息失败');
        console.error(error);
    }
};

// 删除学生信息
const deleteStudent = async (id) => {
    // 实际项目中应该有确认对话框
    if (confirm('确定要删除该学生信息吗？')) {
        try {
            // 这里假设你的删除接口是deleteStudentApi
             await deleteStudentApi(id);
            ElMessage.success('删除成功');
            searchStudents();
        } catch (error) {
            ElMessage.error('删除失败');
            console.error(error);
        }
    }
};

// 提交表单（添加或编辑）
const submitForm = async () => {
    try {
        if (formData.id) {
            // 有ID则是编辑操作
            await updateStudentApi(formData);
            ElMessage.success('更新学生成功');
        } else {
            // 无ID则是添加操作
            await addStudentApi(formData);
            ElMessage.success('添加学生成功');
        }
        closeDialog();
        searchStudents();
    } catch (error) {
        ElMessage.error(formData.id ? '更新学生失败' : '添加学生失败');
        console.error(error);
    }
};

// 页面加载时获取学生列表
onMounted(() => {
    searchStudents();
});
</script>

<style scoped>
.student-management {
    padding: 20px;
}

.search-area {
    margin-bottom: 20px;
}

.action-buttons {
    margin-bottom: 20px;
}

.avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 320px;
    height: 320px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.avatar-uploader .el-icon-plus {
    font-size: 20px;
    color: #909399;
}

.avatar-uploader .el-icon-plus:hover {
    color: #409eff;
}

.avatar {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

:deep(.el-form-item.is-disabled .el-input__inner) {
    background-color: #f5f7fa;
    cursor: not-allowed;
}
</style>
